local SocketManager = class("SocketManager")
local protobuf = require("pbc.protobuf")

local IP = "127.0.0.1"
local PORT = 8083

function SocketManager:ctor()
    self._socketManager = CS.SocketManager.Instance
    self._socketManager:SetLuaEnv(self)
    self._connecting = false
end

function SocketManager:isContenting()
    return self._connecting
end

function SocketManager:onConnected()
    if self._waitMask then
        self._waitMask:showMask(false)
    end
    G_UserData:getBase():c2sLogin()
    if self._onSuccessCall then
        self._onSuccessCall()
    end
end

function SocketManager:onConnectFail()
    if self._waitMask then
        self._waitMask:showMask(false)
    end
    if not self._popupAlert then
        local popAlert = require("view.popup.PopupAlert").new()
        popAlert:updateUI(Lang.get("sys_tip_title"), Lang.get("connected_server_none"))
        popAlert:setCallback(handler(self, self.connectServer))
        self._popupAlert = popAlert
    end
    self._connecting = false
    if self._onFailCall then
        self._onFailCall()
    end
end

function SocketManager:onDisconnect()
    if self._waitMask then
        self._waitMask:showMask(false)
    end
    if not self._popupAlert then
        local popAlert = require("view.popup.PopupAlert").new()
        popAlert:updateUI(Lang.get("sys_tip_title"), Lang.get("connected_server_none"))
        popAlert:setCallback(handler(self, self.connectServer))
        self._popupAlert = popAlert
    end
    self._connecting = false
    if self._onnDisconnectCall then
        self._onnDisconnectCall()
    end
end

function SocketManager:addConnectCallback(onSuccessCallback, onFailCallback, onDisconnectCallback)
    self._onSuccessCall = onSuccessCallback
    self._onFailCall = onFailCallback
    self._onnDisconnectCall = onDisconnectCallback
end

function SocketManager:onRecive(id, buffer, len)
    local messageName = MessageConst[id]
    local messageStruct = "tutorial." .. messageName
    local message = protobuf.decode(messageStruct, buffer, len)
    if rawget(message, "ret") then
        self:_procError(message.ret)
    end
    G_NetWorkManager:dispatch(id, message)
end

function SocketManager:connectServer()
    self._popupAlert = nil
    self._connecting = true
    if not self._waitMask then
        self._waitMask = require("view.common.WaitMask").new()
    end
    self._waitMask:showMask(true)
    self._socketManager:ConnectServer(IP, PORT)
end

function SocketManager:sendMessage(id, param)
    if self._connecting then
        local messageName = MessageConst[id]
        local messageStruct = "tutorial." .. messageName
        local perBuff = protobuf.encode(messageStruct, param)
        self._socketManager:Send(id, perBuff)
    end
end

function SocketManager:_procError(ret)
    if not ret or ret == 1 then
        return
    end
    G_UIManager:showTip("错误：" .. ret)
end

function SocketManager:close()
    self._socketManager:Close()
end

return SocketManager
